package com.liuguangzhou.controller;

import com.alibaba.fastjson.JSONObject;
import com.liuguangzhou.utils.ExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName excelUplodController
 * @Description: TODO
 * @Author liuguangzhou
 * @Date 2020/4/2
 * @Version V1.0
 **/
@Controller
public class ExcelUplodController {
    @RequestMapping("/uploadTest")
    @ResponseBody
    public Object uploadTest(@RequestParam("excelFile") MultipartFile file) {
        JSONObject returnjson = new JSONObject();
        boolean flag = false;
        String msg = "";

        try {
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (!".xlsx".equalsIgnoreCase(fileSuffix) && !".xls".equalsIgnoreCase(fileSuffix)) {
                msg = "文件格式不正确,请选择格式为xlsx的文件";
            } else {
                List<List<String>> lines = ExcelUtil.readExcelToList(file, 0,10, null);
                if (lines.size() == 0) {
                    msg = "模板无有效数据，请重新填写后再进行此操作！";
                } else {
                    Map<String, Map<Integer,String>>  regularMap=ExcelUtil.exceRegular("buAdminRegex.xlsx");
                    List<Map<String, String>> errList = ExcelUtil.validateListData(lines,regularMap.get("buAdminRegex"));
                    //验证通过
                    if (errList.size() == 0) {
                        List<String> listkey = new ArrayList<String>();
                        for (List<String> rows : lines) {
                            String material = rows.get(0);
                            if (StringUtils.isNotBlank(material)) {
                                rows.set(0, material.toUpperCase()); //转成大写
                            }
                        }
//                        插入数据库
//                        utilService.commonBatchInsertTable("ESPA_B_MORE_PREO_BU", listkey, lines);
                    } else {
                        returnjson.put("errList", errList);
                    }
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg = "上传失败";
        }

        returnjson.put("success", flag);
        returnjson.put("msg", msg);
        return returnjson;
    }
}